package com.magi.builder;

import com.magi.core.AppUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.*;

/**
 * Used for building format XML text or file.
 */
public class XmlFileBuilder implements IFileBuilder {
    private final Document document = DocumentHelper.createDocument();

    public XmlFileBuilder(String rootName) {
        document.addElement(rootName);
    }

    public void addDocType(String name, String publicId, String systemId) {
        document.addDocType(name, publicId, systemId);
    }

    @Override
    public String text() {
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setNewlines(true);
            format.setPadText(true);
            return this.formatXml(DocumentHelper.parseText(this.formatXml(document, null)), format);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    private String formatXml(Document xml, OutputFormat format) {
        if (format == null) { format = OutputFormat.createCompactFormat(); }

        try(StringWriter stringWriter = new StringWriter() ){
            XMLWriter writer = new XMLWriter(stringWriter, format);
            writer.setEscapeText(false);
            writer.write(xml);
            return stringWriter.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void writeToFile(String filename) throws IOException {
        AppUtils.writeToFile(filename, this.text());
    }

    public Element getRoot() {
        return document.getRootElement();
    }

    public static void main(String[] args) {
        XmlFileBuilder xmlFileBuilder = new XmlFileBuilder("mapper");
        System.out.println(xmlFileBuilder.text());
    }
}
